#!/usr/bin/python
# author dennis
# 2022年06月19日
import select
import socket
import os
import struct


class Server:
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.s_listen: socket = None

    def tcp_init(self):
        self.s_listen = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s_listen.bind((self.ip, self.port))
        self.s_listen.listen(128)

    def task(self):
        new_client, _ = self.s_listen.accept()
        user = User(new_client)
        user.deal_command()


class User:
    def __init__(self, new_client):
        self.new_client: socket = new_client
        self.user_name = None
        # 获取当前的路径
        self.path = os.getcwd()

    def send_train(self, train_head_bytes):
        train_head = struct.pack('I', len(train_head_bytes))
        self.new_client.send(train_head + train_head_bytes)

    def recv_train(self):
        train_head_bytes = self.new_client.recv(4)
        train_head = struct.unpack('I', train_head_bytes)
        return self.new_client.recv(train_head[0])

    def do_ls(self):
        data = ''
        for file in os.listdir(self.path):
            # 文件名+大小
            data += file + ' ' * 5 + str(os.stat(file).st_size) + '\n'
        self.send_train(data.encode('utf8'))

    def do_cd(self, command):
        path = command.split()[1]
        # 改变目录路径
        os.chdir(path)
        self.path = os.getcwd()
        # 每次客户端执行了cd后，再显示一下路径
        self.send_train(self.path.encode('utf8'))

    def do_pwd(self):
        self.send_train(self.path.encode('utf8'))

    def do_rm(self):
        file_name = self.recv_train().decode('utf8')
        os.remove(file_name)
        self.send_train('删除完毕'.encode('utf8'))

    def do_gets(self):
        file_name = self.recv_train()
        self.send_train(file_name)
        f = open(file_name, 'rb+')
        f_content = f.read()
        self.send_train(f_content)
        f.close()
        self.send_train('下载完成'.encode('utf8'))

    def do_puts(self):
        path = r'E:\gitee\python-fundamentals\6 UDP与TCP通信\文件存储转发器\服务器'
        os.chdir(path)
        file_name = self.recv_train().decode('utf8')
        f = open('【接收】' + file_name, 'wb+')
        file_content = self.recv_train()
        f.write(file_content)
        f.close()
        self.send_train('上传完成'.encode('utf8'))

    def deal_command(self):
        while True:
            command = self.recv_train().decode('utf8')
            if command[:2] == 'ls':
                self.do_ls()
            elif command[:2] == 'cd':
                self.do_cd(command)
            elif command[:3] == 'pwd':
                self.do_pwd()
            elif command[:2] == 'rm':
                self.do_rm()
            elif command[:4] == 'gets':
                self.do_gets()
            elif command[:4] == 'puts':
                self.do_puts()


def main():
    server = Server('', 2000)
    server.tcp_init()
    server.task()


if __name__ == '__main__':
    main()
